<template>
  <div class="repair-add">
    <el-page-header @back="goBack" :title="isView ? '查看报修' : (isEdit ? '编辑报修' : '添加报修')"></el-page-header>
    
    <div class="form-container">
      <el-form 
        ref="repairForm" 
        :model="formData" 
        :rules="rules" 
        label-width="120px"
        :disabled="isView"
      >
        <el-form-item label="所属小区" prop="home.id">
          <el-select v-model="formData.home.id" placeholder="请选择小区" style="width: 100%" @change="handleHomeChange">
            <el-option v-for="home in homeOptions" :key="home.id" :label="home.displayName" :value="home.id"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="报修人" prop="owner.id">
          <el-select v-model="formData.owner.id" placeholder="请选择报修人" style="width: 100%" @change="handleOwnerChange">
            <el-option v-for="owner in ownerOptions" :key="owner.id" :label="owner.name" :value="owner.id"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="联系方式" prop="contact">
          <el-input v-model="formData.contact" placeholder="请输入联系电话"></el-input>
        </el-form-item>
        
        <el-form-item label="报修地址" prop="home.id">
          <el-input v-model="formData.home.displayName" placeholder="请输入报修地址" readonly></el-input>
        </el-form-item>
        
        <el-form-item label="报修类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择报修类型" style="width: 100%">
            <el-option label="水电维修" value="1"></el-option>
            <el-option label="家具维修" value="2"></el-option>
            <el-option label="公共设施" value="3"></el-option>
            <el-option label="其他" value="4"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="紧急程度" prop="urgency">
          <el-radio-group v-model="formData.urgency">
            <el-radio :label="1">一般</el-radio>
            <el-radio :label="2">紧急</el-radio>
            <el-radio :label="3">非常紧急</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="报修内容" prop="description">
          <el-input 
            v-model="formData.description" 
            type="textarea" 
            :rows="4" 
            placeholder="请详细描述报修内容"
          ></el-input>
        </el-form-item>
        
        <el-form-item label="报修时间" prop="reportTime">
          <el-date-picker
            v-model="formData.reportTime"
            type="datetime"
            placeholder="选择日期时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        
        <el-form-item label="处理状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择处理状态" style="width: 100%">
            <el-option label="待处理" :value="0"></el-option>
            <el-option label="处理中" :value="1"></el-option>
            <el-option label="已完成" :value="2"></el-option>
            <el-option label="已取消" :value="3"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="维修人员" prop="repairman" v-if="formData.status > 0">
          <el-input v-model="formData.repairman" placeholder="请输入维修人员姓名"></el-input>
        </el-form-item>
        
        <el-form-item label="维修描述" prop="repairDescription" v-if="formData.status > 0">
          <el-input 
            v-model="formData.repairDescription" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入维修处理描述"
          ></el-input>
        </el-form-item>
        
        <el-form-item label="完成时间" prop="finishTime" v-if="formData.status === 2">
          <el-date-picker
            v-model="formData.finishTime"
            type="datetime"
            placeholder="选择完成时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        
        <el-form-item label="故障图片">
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :limit="5"
            :file-list="fileList"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" v-if="!isView">保存</el-button>
          <el-button @click="goBack">{{ isView ? '返回' : '取消' }}</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { Plus } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';

export default {
  name: 'RepairAdd',
  components: {
    Plus
  },
  data() {
    return {
      isEdit: false,
      isView: false,
      formData: {
        id: null,
        owner: {
          id: null,
          name: ''
        },
        home: {
          id: null,
          building: null,
          name: '',
          displayName: ''
        },
        description: '',
        type: '',
        status: '待处理',
        reportTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
        handleTime: null,
        finishTime: null,
        handlerName: '',
        result: '',
        contact: '',
        urgency: 1,
        repairman: '',
        repairDescription: ''
      },
      ownerOptions: [],
      homeOptions: [],
      fileList: [],
      loading: false,
      rules: {
        'owner.id': [{ required: true, message: '请选择报修人', trigger: 'change' }],
        'home.id': [{ required: true, message: '请选择报修地址', trigger: 'change' }],
        type: [{ required: true, message: '请选择报修类型', trigger: 'change' }],
        description: [{ required: true, message: '请输入报修内容', trigger: 'blur' }],
        status: [{ required: true, message: '请选择处理状态', trigger: 'change' }]
      }
    };
  },
  created() {
    // 加载业主和房屋选项
    this.fetchOwners();
    this.fetchHomes();
    
    const id = this.$route.query.id;
    const view = this.$route.query.view;
    
    if (id) {
      this.isEdit = true;
      if (view === 'true') {
        this.isView = true;
      }
      this.fetchRepairData(id);
    }
  },
  methods: {
    // 获取业主列表
    fetchOwners() {
      axios.get('/api/owners')
        .then(response => {
          let owners = [];
          if (Array.isArray(response.data)) {
            owners = response.data;
          } else if (response.data && Array.isArray(response.data.content)) {
            owners = response.data.content;
          }
          
          // 确保每个业主对象都有必要的字段
          this.ownerOptions = owners.map(owner => ({
            id: owner.id,
            name: owner.name,
            phoneNumber: owner.phoneNumber || owner.phone || ''
          }));
        })
        .catch(error => {
          console.error('获取业主列表失败:', error);
          ElMessage.error('获取业主列表失败');
        });
    },
    
    // 获取房屋列表
    fetchHomes() {
      axios.get('/api/homes')
        .then(response => {
          if (Array.isArray(response.data)) {
            this.homeOptions = response.data;
          } else if (response.data && Array.isArray(response.data.content)) {
            this.homeOptions = response.data.content;
          } else {
            this.homeOptions = [];
          }
          
          // 添加显示名称
          this.homeOptions.forEach(home => {
            let displayName = '';
            
            // 添加楼栋信息
            if (home.building && home.building.name) {
              displayName += home.building.name;
            }
            
            // 添加房屋名称
            if (home.name) {
              displayName += ' ' + home.name;
            }
            
            home.displayName = displayName || '未知地址';
          });
        })
        .catch(error => {
          console.error('获取房屋列表失败:', error);
          ElMessage.error('获取房屋列表失败');
        });
    },
    
    // 处理业主选择变更
    handleOwnerChange(ownerId) {
      const selectedOwner = this.ownerOptions.find(owner => owner.id === ownerId);
      if (selectedOwner) {
        this.formData.owner.name = selectedOwner.name;
        // 自动填充联系方式
        if (selectedOwner.phoneNumber) {
          this.formData.contact = selectedOwner.phoneNumber;
        }
      }
    },
    
    // 处理房屋选择变更
    handleHomeChange(homeId) {
      const selectedHome = this.homeOptions.find(home => home.id === homeId);
      if (selectedHome) {
        this.formData.home.building = selectedHome.building;
        this.formData.home.name = selectedHome.name;
        this.formData.home.displayName = selectedHome.displayName;
      }
    },
    
    fetchRepairData(id) {
      this.loading = true;
      axios.get(`/api/repairs/${id}`)
        .then(response => {
          const data = response.data;
          
          // 确保owner和home对象存在
          if (!data.owner) data.owner = { id: null, name: '' };
          if (!data.home) data.home = { id: null, building: null, name: '' };
          
          // 构建显示地址
          let displayName = '';
          if (data.home) {
            // 添加楼栋信息
            if (data.home.building && data.home.building.name) {
              displayName += data.home.building.name;
            }
            
            // 添加房屋名称
            if (data.home.name) {
              displayName += ' ' + data.home.name;
            }
          }
          
          // 转换状态为数字
          let statusNumber = 0;
          if (data.status === '处理中') statusNumber = 1;
          else if (data.status === '已完成') statusNumber = 2;
          else if (data.status === '已取消') statusNumber = 3;
          
          // 更新表单数据
          this.formData = {
            id: data.id,
            owner: {
              id: data.owner.id,
              name: data.owner.name || ''
            },
            home: {
              id: data.home.id,
              building: data.home.building,
              name: data.home.name || '',
              displayName: displayName || '未知地址'
            },
            description: data.description || '',
            type: data.type || '',
            status: statusNumber,
            reportTime: data.reportTime ? new Date(data.reportTime).toISOString().slice(0, 19).replace('T', ' ') : null,
            handleTime: data.handleTime ? new Date(data.handleTime).toISOString().slice(0, 19).replace('T', ' ') : null,
            finishTime: data.finishTime ? new Date(data.finishTime).toISOString().slice(0, 19).replace('T', ' ') : null,
            handlerName: data.handlerName || '',
            result: data.result || '',
            contact: data.owner?.phoneNumber || '',
            urgency: 1,
            repairman: data.handlerName || '',
            repairDescription: data.result || ''
          };
          
          this.loading = false;
        })
        .catch(error => {
          console.error('获取维修信息失败:', error);
          ElMessage.error('获取维修信息失败');
          this.loading = false;
        });
    },
    
    submitForm() {
      this.$refs.repairForm.validate(valid => {
        if (valid) {
          this.loading = true;
          
          // 构建提交数据 - 按照后端API需要的格式
          const submitData = {
            id: this.formData.id,
            owner: {
              id: this.formData.owner.id
            },
            home: {
              id: this.formData.home.id
            },
            description: this.formData.description,
            type: this.formData.type,
            status: this.formData.status === 0 || this.formData.status === '待处理' ? '待处理' : 
                   this.formData.status === 1 || this.formData.status === '处理中' ? '处理中' : 
                   this.formData.status === 2 || this.formData.status === '已完成' ? '已完成' : 
                   this.formData.status === 3 || this.formData.status === '已取消' ? '已取消' : '待处理',
            reportTime: this.formData.reportTime ? new Date(this.formData.reportTime).getTime() : new Date().getTime(),
            handlerName: this.formData.repairman || this.formData.handlerName || '',
            result: this.formData.repairDescription || this.formData.result || ''
          };
          
          // 根据状态设置相关时间
          if (this.formData.status === 1 || this.formData.status === '处理中') {
            submitData.handleTime = this.formData.handleTime ? 
              new Date(this.formData.handleTime).getTime() : 
              new Date().getTime();
          }
          
          if (this.formData.status === 2 || this.formData.status === '已完成') {
            submitData.finishTime = this.formData.finishTime ? 
              new Date(this.formData.finishTime).getTime() : 
              new Date().getTime();
          }
          
          console.log('提交的数据:', submitData); // 调试日志
          
          if (this.isEdit) {
            // 更新维修信息
            axios.put(`/api/repairs/${submitData.id}`, submitData)
              .then(response => {
                console.log('更新响应:', response.data);
                ElMessage.success('更新维修信息成功');
                this.goBack();
              })
              .catch(error => {
                console.error('更新维修信息失败:', error);
                ElMessage.error('更新维修信息失败');
              })
              .finally(() => {
                this.loading = false;
              });
          } else {
            // 新增维修信息
            axios.post('/api/repairs', submitData)
              .then(response => {
                console.log('添加响应:', response.data);
                ElMessage.success('新增维修信息成功');
                this.goBack();
              })
              .catch(error => {
                console.error('新增维修信息失败:', error);
                ElMessage.error('新增维修信息失败: ' + (error.response?.data?.message || error.message));
              })
              .finally(() => {
                this.loading = false;
              });
          }
        } else {
          return false;
        }
      });
    },
    
    goBack() {
      this.$router.push('/property/service/repair');
    }
  }
};
</script>

<style scoped>
.repair-add {
  padding: 20px;
}
.form-container {
  margin-top: 20px;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>
